package cn.dkk.Spring.framework.beans.factory.support.xml;

import cn.dkk.Spring.framework.beans.BeanDefinition;
import cn.dkk.Spring.framework.beans.MutablePropertyValues;
import cn.dkk.Spring.framework.beans.PropertyValue;
import cn.dkk.Spring.framework.beans.factory.support.BeanDefinitionReader;
import cn.dkk.Spring.framework.beans.factory.support.BeanDefinitionRegistry;
import cn.dkk.Spring.framework.beans.factory.support.SimpleBeanDefinitionRegistry;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @author dkk
 * @date 2022/8/3
 * @desc
 */
public class XmlBeanDefinitionReader implements BeanDefinitionReader {

    private BeanDefinitionRegistry registry ;

    public XmlBeanDefinitionReader() {
        registry=new SimpleBeanDefinitionRegistry();
    }

    @Override
    public BeanDefinitionRegistry getRegistry() {
        return registry;
    }

    @Override
    public void loadBeanDefinitions(String configLocation) throws Exception {
        // 使用dom4j进行xml的解析
        SAXReader reader= new SAXReader();
        // 获取项目跟路径下的配置文件输入流
        InputStream resourceAsStream = XmlBeanDefinitionReader.class.getClassLoader().getResourceAsStream(configLocation);
        // 读取文档对象
        Document document = reader.read(resourceAsStream);
        // 获取跟标签
        Element rootElement = document.getRootElement();
        // 获取根标签下的所有bean标签对象
        List<Element> elements = rootElement.elements("bean");
        for (Element element : elements) {
            // 获取id属性
            String id = element.attributeValue("id");
            // 获取class属性
            String className = element.attributeValue("class");
            // 封装到BeanDefinition对象中
            BeanDefinition beanDefinition = new BeanDefinition();
            beanDefinition.setId(id);
            beanDefinition.setClassName(className);
            // 获取bean标签下的property标签
            List<Element> properties = element.elements("property");
            // 准备封装MutableProperty TODO mutablePropertyValues是否需要new
            MutablePropertyValues mutablePropertyValues = beanDefinition.getMutablePropertyValues();
            for (Element property : properties) {
                // 获取value中的属性
                PropertyValue propertyValue = new PropertyValue(
                        property.attributeValue("name"),
                        property.attributeValue("ref"),
                        property.attributeValue("value")
                );
                // 添加到mutablePropertyValues中
                mutablePropertyValues.add(propertyValue);
            }
            registry.registryBeanDefinition(id,beanDefinition);
        }
    }

}
